package cn.bellychang.wangzheng.stack;

import cn.bellychang.bobo.stack.Stack;

/**
 * @author ChangLiang
 * @date 2021/1/28
 */
public class StackBasedOnLinkedList<E> implements Stack<E> {

    /**
     * 栈顶指针
     */
    private Node<E> top = null;

    private int count;

    @Override
    public int size() {
        return count;
    }

    @Override
    public boolean isEmpty() {
        return count==0;
    }

    @Override
    public void push(E e) {
        if (count == 0) {
            top = new Node<>(e, null);
        } else {
            Node<E> temp = top;
            top = new Node<>(e, temp);
        }
        count++;
    }

    @Override
    public E pop() {
        if (count == 0) {
            throw new RuntimeException("stack is empty");
        } else {
            Node<E> temp = top;
            top = top.next;
            count--;
            return temp.data;
        }
    }

    @Override
    public E peek() {
        return top.data;
    }

    private static class Node<E>{
        private E data;
        private Node<E> next;

        public Node(E data, Node<E> next) {
            this.data = data;
            this.next = next;
        }
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("Stack Top{");
        Node<E> temp = top;
        while (temp != null) {
            builder.append(temp.data).append("->");
            temp = temp.next;
        }
        return builder.toString().endsWith("->") ?
                builder.substring(0, builder.length() - 2) + "}"
                : builder.append("}").toString();
    }
}
